package com.ja.openchat.viewmodels;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.fragment.app.FragmentActivity;

import com.blankj.utilcode.util.ActivityUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.ja.openchat.data.TabExMenuResult;
import com.ja.openchat.http.HttpUtil;
import com.ja.openchat.ui.OuterShareActivity;
import com.ja.openchat.ui.chat.ChatActivity;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.config.TabExMenuInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.version.AppVersionInfo;
import com.ja.openchat.ui.update.UpdateInfo;
import com.ja.openchat.ui.update.UpdateManager;
import com.ja.openchat.ui.update.UpdateUtil;
import com.zy.openchat.util.LocalNotificationHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;

public class MainViewModel extends BaseViewModel {

    private final Application application;
    public ObservableField<Integer> msgUnreadTotalCount = new ObservableField<>(0);
    public ObservableField<Boolean> isHandleViewIntent = new ObservableField<>(false);
    public SingleLiveEvent<Integer> mCircleUnreadCount = new SingleLiveEvent<>();
    public SingleLiveEvent<TabExMenuInfo> mTabExMenuInfoEvent = new SingleLiveEvent<>();
    public MainViewModel(@NonNull Application application, BaseModel mRepository) {
        super(application);
        this.application = application;
    }





    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_Message_Total_Unread_Changed:
                //未读总数变化
                refreshUnreadCountView();
                break;
            case EUser_Td_Connection_State_Changed:
                syncServerData((FragmentActivity) ActivityUtils.getTopActivity());
                break;
            case EUser_Tab_Ex_Menu_Changed:
                TabExMenuInfo menuInfo = TabExMenuInfo.getTabExMenuInfo();
                if(menuInfo!=null){
                    mTabExMenuInfoEvent.setValue(menuInfo);
                }
                refreshUnreadCountView();
                break;
            case EUser_Td_update_Circle_Unread_count:
                mCircleUnreadCount.setValue(TelegramManager.getTelegramManager().mCircleUnreadCount);
                break;
            default:
                break;
        }
    }

    public void refreshUnreadCountView() {
        msgUnreadTotalCount.set(UserInfo.getUserInfo().msgUnreadTotalCount);
    }


    public void doNotificationIntent(Intent intent) {
        if (intent != null) {
            int type = intent.getIntExtra("notication_type", -1);
            if (type == LocalNotificationHelper.LOCAL_NOTIFICATION_TYPE_MESSAGE) {//消息
                String json = intent.getStringExtra("msg");
                doMsg(json);
            }
        }
    }

    public void doMsg(String msgJson) {
        MessageInfo msg = new Gson().fromJson(msgJson, MessageInfo.class);
        ChatInfo chat = TelegramManager.getTelegramManager().getTgData().chatInfo(msg.chat_id);
        if (chat != null) {
            ChatActivity.startActivity(application, chat);
        }
    }


    public void silentUpdate(Activity mainActivity) {
        TelegramManager.getTelegramManager().getAppVersion(getApplication(), UpdateUtil.getVersionCode(getApplication()), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (obj.ok && obj.data != null && obj.data instanceof AppVersionInfo) {
                    AppVersionInfo versionInfo = (AppVersionInfo) obj.data;
                    UpdateInfo updateInfo = new UpdateInfo();
                    updateInfo.hasUpdate = true;
                    updateInfo.url = versionInfo.downloadUrl;
                    updateInfo.versionCode = versionInfo.versionCode;
                    updateInfo.versionName = versionInfo.version;
                    UpdateManager.create(mainActivity).setNotifyId(999).setManual(false).setUpdateInfo(updateInfo).check();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }




    //同步任务
    public void syncTabExMenu() {
//        TelegramManager.getTelegramManager().queryTabExMenu(getApplication(), new TgResultBlock<TabExMenuInfo>() {
//            @Override
//            public void onResult(Map<String, Object> request, JsonObject response, TabExMenuInfo obj) {
//                if (obj != null) {
//                    TabExMenuInfo.saveTabExMenuInfo(obj);
//                }
//            }
//
//            @Override
//            public void onTimeout(Map<String, Object> request) {
//
//            }
//        });

        HttpUtil.getMiddleMenuInfo("get_custom_page_list", new AbsCallback<TabExMenuResult>() {
            @Override
            public void onSuccess(Response response) {
                TabExMenuResult result = (TabExMenuResult) response.body();
                if(result != null && TextUtils.equals("success",result.msg)){
                    if(result.data != null && result.data.size() > 0){
                        TabExMenuInfo info = new TabExMenuInfo();
                        info.icon = result.data.get(0).site_logo;
                        info.url = result.data.get(0).site_url;
                        info.title = result.data.get(0).site_name;
//                        info.title = "测试";
                        info.status = result.data.get(0).status+"";
//                        info.status = "0";
                        TabExMenuInfo.saveTabExMenuInfo(info);

//                        new Handler().postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                info.status = "1";
//                                TabExMenuInfo.saveTabExMenuInfo(info);
//
//                            }
//                        },7000);
                    }
                }
            }

            @Override
            public TabExMenuResult convertResponse(okhttp3.Response response) throws Throwable {
                String result = response.body().string();
                return new Gson().fromJson(result, TabExMenuResult.class);
            }
        });
    }

    private void syncAppConfig() {
        TelegramManager.getTelegramManager().queryAppConfig(getApplication(), new TgResultBlock<AppConfigInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, AppConfigInfo obj) {
                if (obj != null) {
                    AppConfigInfo.saveAppConfigInfo(obj);
                    //发送通知
                    EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.EUser_App_Config_Changed, null));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    public void syncServerData(FragmentActivity context) {
        if (TelegramManager.getTelegramManager().getTgData().getUserConnectionState() == TelegramManager.GoUserConnectionState.GoUserConnectionState_StateReady) {
            if(isHandleViewIntent.get()){
                OuterShareActivity.handleViewIntent(context, context.getIntent());
                isHandleViewIntent.set(false);
            }
            //同步tab扩展菜单
            syncTabExMenu();
            //同步app全局配置
            syncAppConfig();
        }
    }

}
